package com.scpii.universal.struts.produce;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.google.zxing.WriterException;
import com.scpii.universal.action.BaseAction;
import com.scpii.universal.constant.ExceptionConstants;
import com.scpii.universal.constant.GenericConstants;
import com.scpii.universal.dto.UserInfoDto;
import com.scpii.universal.hibernate.entity.AppIconTab;
import com.scpii.universal.hibernate.entity.AppStyleImgTab;
import com.scpii.universal.hibernate.entity.AppStyleTab;
import com.scpii.universal.hibernate.entity.AppTab;
import com.scpii.universal.hibernate.entity.AppUpdateTab;
import com.scpii.universal.pb.UniversalProtocol.QryFinishComplieTaskSC;
import com.scpii.universal.service.AppIconService;
import com.scpii.universal.service.AppService;
import com.scpii.universal.service.AppStyleService;
import com.scpii.universal.service.AppUpdateService;
import com.scpii.universal.service.PbInterfaceService;
import com.scpii.universal.util.FileUploadUtil;
import com.scpii.universal.util.ImgAndFilePath;
import com.scpii.universal.util.IosDownload;
import com.scpii.universal.util.QRCodeProduceUtil;

/**
 * universalWeb
 * @author liuhj
 * 2012-7-10下午11:05:22
 */
@Controller
@Scope("prototype")
public class AppProcessAction extends BaseAction {

	private static final long serialVersionUID = 2994397432224332164L;
	private List<AppStyleTab> listAppStyles;
	private Integer id;
	private String json;
	private String imgLogoURL;
	private AppIconTab appIconTab;
	
	@Resource
	private AppStyleService appStyleService;
	@Resource
	private AppService appService;
	@Resource 
	private AppIconService appIconService;
	@Resource
	private PbInterfaceService pbInterfaceService;
	@Resource
	private AppUpdateService appUpdateService;
	private Log log = LogFactory.getLog(this.getClass());
	
	/**
	 * 查询所有应用风格
	 * @return
	 * @author liuhj
	 * 2012-7-10下午11:10:06
	 */
	public String listAllStyle() {
		this.setListAppStyles(appStyleService.getList(
				GenericConstants.LOGIC_DELETE_SIGN,GenericConstants.DELETE_SIGN_EXIST));
		return SUCCESS;
	}
	
	/**
	 * 创建应用
	 * @return
	 * @author liuhj
	 * 2012-7-10下午11:13:36
	 * @throws IOException 
	 */
	public String createApp() throws IOException {
		json = URLDecoder.decode(json, "GBK");
		json = json.trim().substring(1, json.length()-1).replaceAll("\\\\", "");
		String errMsg = validateAppInfo(json);
		if (errMsg != null) {
			//校验错误
			jsonOut(errMsg);
			return null;
		}
		UserInfoDto user = getUserInfo();
		int[] result = appService.saveApp(json, user,
				getWebAppsRealPath(), ImgAndFilePath.ENTERP_WORK_DIR + "_"
				+ user.getIntEnterpId());
		user.setAppId(result[0]);//保存应用ID
		//保存loading icon id至session
		user.setAppLoadingIconId(result[1]);
		return null;
	}
	
	/**
	 * 更新应用信息
	 * @return
	 * @author liuhj
	 * 2012-8-5下午06:09:45
	 * @throws IOException 
	 */
	public String updateApp() throws IOException {
		json = URLDecoder.decode(json, "GBK");
		json = json.trim().substring(1, json.length()-1).replaceAll("\\\\", "");
		String errMsg = validateAppInfo(json);
		if (errMsg != null) {
			//校验错误
			jsonOut(errMsg);
			return null;
		}
		UserInfoDto user = getUserInfo();
		appService.updateApp(json, user, getWebAppsRealPath(),
				ImgAndFilePath.ENTERP_WORK_DIR + "_" + user.getIntEnterpId());
		String relativePath = getServerURL()+getImgBasePath().replaceAll("\\\\", "/") + "/ICON/";
		String targetFileName = user.getAppId()+"_"+GenericConstants.APP_LOGO_SUFFIX;
		jsonOut("{\"iconUrl\":\""+relativePath+targetFileName+"\"}");
		return null;
	}
	
	/**
	 * 校验应用输入的信息
	 * @param appTab
	 * @param iconURL
	 * @return
	 * @author liuhj
	 * 2012-7-14下午10:23:30
	 */
	private String validateAppInfo(String json) {
		JSONObject jo = JSONObject.fromObject(json);
		if (StringUtils.isBlank(jo.getString("varAppName"))) {
			return ExceptionConstants.APP_NAME_NULL_ERROR;
		}
		if (StringUtils.isBlank(jo.getString("varAppImgUrl"))) {
			return ExceptionConstants.APP_STYLE_NULL_ERROR;
		}
		if (StringUtils.isBlank(jo.getString("intAppStyleId"))) {
			return ExceptionConstants.APP_STYLE_NULL_ERROR;
		}
		return null;
	}
	
	/**
	 * 根据ID获得应用相关信息
	 * @return
	 * @author liuhj
	 * 2012-7-11下午02:29:53
	 * @throws IOException 
	 */
	public String viewApp() throws IOException {
		AppTab app = appService.get(getUserInfo().getAppId());
		JSONObject datas = new JSONObject();
		datas.put("intAppId", getUserInfo().getAppId());
		datas.put("varAppName", app.getVarAppName());
		datas.put("varAppDescript", app.getVarAppDescript());
		datas.put("intAppStyleId", app.getIntAppStyleId());
		Integer iconId = getUserInfo().getAndroidVersionUpdate().getIntIconId();
		datas.put("intIconId", (iconId == null || iconId <= 0) ? -1 : iconId);
		datas.put("varAppImgUrl", (iconId == null || iconId <= 0) ? ""
				: appIconService.getIconURLById(iconId));
		datas.put("varCountData", app.getVarCountData());
		jsonOut("{\"appInfo\":" + datas.toString() + "}");
		return null;
	}
	
	/**
	 * 应用图标上传
	 * @return
	 * @throws IOException
	 * @author liuhj
	 * 2012-7-12下午03:05:17
	 */
	public String appIconUpload() throws IOException {
		String fileName = (String) session.getAttribute(GenericConstants.TEMP_APP_ICON_SESSION);
		String tempFolder = getWebAppsRealPath() + ImgAndFilePath.TEMP_FOLDER;
		File file = new File(tempFolder);
		if (!file.exists()) {
			file.mkdirs();
		}
		String imgDiskPath = getWebAppsRealPath() + ImgAndFilePath.TEMP_FOLDER+ File.separator + fileName;
		String imgURLPath = ImgAndFilePath.TEMP_FOLDER+ File.separator + fileName;
		FileUploadUtil.fileUpload(imgDiskPath, request);//上传
		//返回icon服务器上的URL
		this.setImgLogoURL(getServerURL()+imgURLPath.replace("\\", "/"));
		log.info("上传应用图标到临时文件夹成功");
		return SUCCESS;
	}
	
	/**
	 * 应用Loading图片上传
	 * @return
	 * @author liuhj
	 * 2012-7-15上午12:27:09
	 */
	public String appLoadingUpload() {
		String fileName = getUserInfo().getAppId()+"_"+GenericConstants.APP_LOADING_SUFFIX;
		String imgURLPath = getImgBasePath()+ImgAndFilePath.ENTERP_LOADING+File.separator + fileName;
		String imgDiskPath = getWebAppsRealPath() + imgURLPath;
		FileUploadUtil.fileUpload(imgDiskPath, request);//上传
		//返回icon服务器上的URL
		String loadingURL = getServerURL()+imgURLPath.replace("\\", "/");
		this.setImgLogoURL(loadingURL);
		//更新LOADING ICON URL
		appIconService.updateLoadingIcon(getUserInfo().getAppLoadingIconId(), loadingURL);
		return SUCCESS;
	}
	
	/**
	 * 查看应用LOADING图片
	 * @return
	 * @author liuhj
	 * 2012-7-13下午01:47:15
	 * @throws IOException 
	 */
	public String viewAppLoading() throws IOException {
		AppUpdateTab andrUpd = getUserInfo().getAndroidVersionUpdate();
		if (andrUpd == null || andrUpd.getIntLoadingIconId() == null || andrUpd.getIntLoadingIconId() <= 0) {
			jsonOut(ExceptionConstants.APP_LOADING_NULL);
			return null;
		}
		Integer loadingIconId = andrUpd.getIntLoadingIconId();
		JSONObject datas = new JSONObject();
		datas.put("intIconId", loadingIconId);
		datas.put("varIconUrl", appIconService.getIconURLById(loadingIconId));
		jsonOut("{\"loadingInfo\":" + datas.toString() + "}");
		return null;
	}
	
	/**
	 * 检测用户走到了创建应用的哪一步
	 * @return
	 * @author liuhj
	 * 2012-7-27下午04:29:33
	 * @throws IOException 
	 */
	public String checkWhichStep() throws IOException{
		if (getUserInfo() == null) {
			//还未登录
			jsonOut("-1");
		} else if (getUserInfo().getAppId() == null || getUserInfo().getAppId() == 0) {
			//还未创建应用
			jsonOut("0");
		} else if (StringUtils.isBlank(appIconService
				.getIconURLById(getUserInfo().getAppLoadingIconId() == null ? 0
						: getUserInfo().getAppLoadingIconId()))) {
			// 还未上传Loading图片
			jsonOut("1");
		} else {
			jsonOut("2");
		}
		return null;
	}
	
	/**
	 * 创建安卓编译任务
	 * @return
	 * @author liuhj
	 * 2012-8-2下午04:32:01
	 * @throws IOException 
	 */
	public String createAndrCompile() throws IOException {
		boolean result = appService.checkIfCanproduceApp(getUserInfo());
		JSONObject datas = new JSONObject();
		if (result) {
			datas.put("result", String.valueOf(createComplieTask(
					GenericConstants.OPERATION_SYS_ANDROID)));
		} else {
			//应用没有至少一个页面，不能生成应用
			datas.put("result", "-1");
		}
		jsonOut(datas.toString());
		return null;
	}
	
	/**
	 * 创建IOS编译任务
	 * @return
	 * @author liuhj
	 * 2012-8-2下午04:32:01
	 * @throws IOException 
	 */
	public String produceIosApp() throws IOException {
		boolean result = appService.checkIfCanproduceApp(getUserInfo());
		JSONObject datas = new JSONObject();
		if (result) {
			datas.put("result", String.valueOf(createComplieTask(
					GenericConstants.OPERATION_SYS_IOS)));
		} else {
			//应用没有至少一个页面，不能生成应用
			datas.put("result", "-1");
		}
		jsonOut(datas.toString());
		return null;
	}
	
	/**
	 * 创建编译任务
	 * @param type
	 * 			0成功，1失败
	 * @return
	 * @author liuhj
	 * 2012-8-15下午04:03:30
	 * @throws IOException 
	 */
	private int createComplieTask(int type) throws IOException {
		//执行编译时创建一个应用版本
		AppUpdateTab appUpd = appService.saveAppVersionUpdate(getUserInfo(), type);
		if (type == GenericConstants.OPERATION_SYS_ANDROID) {
			getUserInfo().setAndroidVersionUpdate(appUpd);
		} else {
			getUserInfo().setIosVersionUpdate(appUpd);
		}
		//获取风格Id
		AppTab app = appService.getAppInfo(getUserInfo().getAppId(),
				new String[] { "varAppName", "intAppStyleId" });
		Integer response = 1;
		// 执行编译任务
		response = pbInterfaceService.creatComplieTask(appUpd
				.getIntAppUpdateId(), appUpd.getIntAppOsType(), appUpd
				.getVarAppSign(), app.getVarAppName(), appUpd
				.getDobAppVersion(), app.getIntAppStyleId());
		return response;
	}
	
	/**
	 * 获取编译生成的URL
	 * @param pAppUpd
	 * @return
	 * @author liuhj
	 * 2012-8-13上午09:13:28
	 * @throws IOException 
	 */
	private String getProducedAppUrl(AppUpdateTab pAppUpd) throws IOException {
		IosDownload overRideIosUrl = null;
		String resultUrl = null;
		int iconId = pAppUpd.getIntIconId();
		int appId = getUserInfo().getAppId();
		log.info("开始获取完成的编译任务");
		QryFinishComplieTaskSC lstFinshedTask = pbInterfaceService.qryComplieTask(
				pAppUpd.getIntAppUpdateId());
		if (lstFinshedTask.getFinishComplieTaskList().size() <= 0) {
			return resultUrl;
		}
		int status = lstFinshedTask.getFinishComplieTask(0).getStatus();
		if (status == -1) {
			//获取URL失败
			return "-1";
		}
		String url = lstFinshedTask.getFinishComplieTask(0).getUrl();
		log.info("获取到编译后的URL为："+url);
		resultUrl = url;
		if (!StringUtils.isBlank(url)) {
			String installUrl = null;
			if (pAppUpd.getIntAppOsType() == GenericConstants.OPERATION_SYS_IOS) {
				String[] urls = StringUtils.split(url,",");
				String gotoappUrl = urls[0].contains("_gotoapp.ipa")?urls[0]:urls[1];
				overRideIosUrl = new IosDownload(appId, gotoappUrl, appIconService
						.getIconURLById(iconId),appService.getAppName(appId));
				String relativePath = getImgBasePath()
						+ ImgAndFilePath.IOS_DLIST +File.separator+ "universal_" + appId
						+ ".plist";
				String pListPath = getWebAppsRealPath() + relativePath;
				overRideIosUrl.getIosDownloadUrl(pListPath);
				installUrl = "itms-services://?action=download-manifest&url="
						+ getServerURL() + relativePath.replaceAll("\\\\", "/");
				pAppUpd.setVarIosInstallUrl(installUrl);
			}
			// 更新URL
			pAppUpd.setVarAppDownloadUrl(url);
			appService.updateAppDownloadUrl(url, installUrl, pAppUpd
					.getIntAppUpdateId());
		}
		return resultUrl;
	}
	
	/**
	 * 获取android下载地址
	 * @return
	 * @throws IOException
	 * @author liuhj
	 * 2012-8-15下午06:54:07
	 * @throws WriterException 
	 */
	public String getAndroidDownLoadUrl() throws IOException, WriterException {
		JSONObject datas = new JSONObject();
		String url = getProducedAppUrl(getUserInfo().getAndroidVersionUpdate());
		datas.put("url", url);
		if (!StringUtils.isBlank(url) && !"-1".equals(url)) {
			String relativeUrl = getImgBasePath() + File.separator + "androidQRcode.png";
			String path = getWebAppsRealPath() + relativeUrl;
			String port = String.valueOf(request.getServerPort());
			if("80".equals(port)){
				port = "";
			}else{
				port = ":"+port;
			}
			String pageUrl = request.getScheme() + "://"+ request.getServerName()  + port + request.getContextPath() + "/ad.jsp?a="+getUserInfo().getAppId();
			produceQRcode(pageUrl, path);
			//二维码地址
			datas.put("QRcodeURL", getServerURL()
					+ relativeUrl.replaceAll("\\\\", "/"));
		} else {
			datas.put("QRcodeURL",null);
		}
		jsonOut(datas.toString());
		return null;
	}
	
	/**
	 * 获取IOS下载地址
	 * @return
	 * @throws IOException
	 * @author liuhj
	 * 2012-8-15下午06:54:07
	 * @throws WriterException 
	 */
	public String getIosDownLoadUrl() throws IOException, WriterException {
		JSONObject datas = new JSONObject();
		String url = getProducedAppUrl(getUserInfo().getIosVersionUpdate());
		if (!StringUtils.isBlank(url) && !"-1".equals(url)) {
			String[] urls = StringUtils.split(url,",");
			String appStoreUrl = urls[0].contains("_appstore.ipa")?urls[0]:urls[1];
			String gotoappUrl = urls[0].contains("_gotoapp.ipa")?urls[0]:urls[1];
			datas.put("appStoreUrl", appStoreUrl);
			datas.put("gotoappUrl", gotoappUrl);
			
			String relativeUrl = getImgBasePath() + File.separator + "IosQRcode.png";
			String path = getWebAppsRealPath() + relativeUrl;
			String port = String.valueOf(request.getServerPort());
			if("80".equals(port)){
				port = "";
			}else{
				port = ":"+port;
			}
			String pageUrl = request.getScheme() + "://"+ request.getServerName()  + port  + request.getContextPath() + "/sd.jsp?a="+getUserInfo().getAppId()+"&e="+getUserInfo().getIntEnterpId();
			produceQRcode(pageUrl, path);
			//二维码地址
			datas.put("QRcodeURL", getServerURL()
					+ relativeUrl.replaceAll("\\\\", "/"));
		} else if("-1".equals(url)) {
			datas.put("appStoreUrl", "-1");
			datas.put("gotoappUrl", "-1");
			datas.put("QRcodeURL",null);
		} else {
			datas.put("appStoreUrl", url);
			datas.put("gotoappUrl", url);
			datas.put("QRcodeURL",null);
		}
		jsonOut(datas.toString());
		return null;
	}
	
	/**
	 * 查看标题背景
	 * @return
	 * @author liuhj
	 * 2012-8-3上午09:32:38
	 * @throws IOException 
	 */
	public String viewTitleBGImg() throws IOException{
		AppUpdateTab andrUpd = getUserInfo().getAndroidVersionUpdate();
		if (andrUpd == null) {
			jsonOut(GenericConstants.OPERATION_NULL);
			return null;
		}
		AppIconTab icon = loadStyleImg(GenericConstants.STYLE_TYPE_TITLE, andrUpd.getIntAppTitleBgImgId());
		JSONObject datas = new JSONObject();
		if (icon != null) {
			datas.put("intIconId", icon.getIntIconId());
			datas.put("varIconUrl", icon.getVarIconUrl());
		} else {
			datas.put("intIconId", "-1");
			datas.put("varIconUrl", "-1");
		}
		AppIconTab secIcon = loadStyleImg(GenericConstants.STYLE_TYPE_TITLE, andrUpd.getIntAppSecondTitleImgId());
		if (secIcon == null) {
			datas.put("intSecondIconId", "-1");
			datas.put("varSecondIconUrl", "-1");
		} else {
			datas.put("intSecondIconId", secIcon.getIntIconId());
			datas.put("varSecondIconUrl", secIcon.getVarIconUrl());
		}
		jsonOut(datas.toString());
		return null;
	}
	
	
	/**
	 * 查看应用背景
	 * @return
	 * @author liuhj
	 * 2012-8-3上午09:32:38
	 * @throws IOException 
	 */
	public String viewAppBGImg() throws IOException{
		AppUpdateTab andrUpd = getUserInfo().getAndroidVersionUpdate();
		if (andrUpd == null) {
			jsonOut(GenericConstants.OPERATION_NULL);
			return null;
		}
		AppIconTab icon = loadStyleImg(GenericConstants.STYLE_TYPE_APP_BackGROUND, andrUpd.getIntAppBackgImgId());
		if (icon == null) {
			jsonOut(GenericConstants.OPERATION_NULL);
			return null;
		}
		this.setAppIconTab(icon);
		return SUCCESS;
	}
	
	/**
	 * 查看导航背景
	 * @return
	 * @author liuhj
	 * 2012-8-3上午09:32:38
	 * @throws IOException 
	 */
	public String viewNavigationBGImg() throws IOException{
		AppUpdateTab andrUpd = getUserInfo().getAndroidVersionUpdate();
		if (andrUpd == null) {
			jsonOut(GenericConstants.OPERATION_NULL);
			return null;
		}
		AppIconTab icon = loadStyleImg(GenericConstants.STYLE_TYPE_NAV, andrUpd.getIntAppNavigateBgImgId());
		if (icon == null) {
			jsonOut(GenericConstants.OPERATION_NULL);
			return null;
		}
		this.setAppIconTab(icon);
		return SUCCESS;
	}
	
	/**
	 * 根据图片类型获得风格图片URL
	 * @param type
	 * @param iconId
	 * @return
	 * @author liuhj
	 * 2012-8-11下午09:33:27
	 */
	private AppIconTab loadStyleImg(int type,Integer iconId) {
		AppTab appTab = appService.getAppInfo(getUserInfo().getAppId(),
				new String[] { "intAppStyleId" });
		AppIconTab icon = new AppIconTab();
		Integer styleId = appTab.getIntAppStyleId();
		if (iconId != null && iconId > 0) {
			//自定义风格
			String url = appIconService.getIconURLById(iconId);
			icon.setIntIconId(iconId);
			//解决浏览器缓存图片
			icon.setVarIconUrl(url + "?rand="+Math.random()*100);
		} else if (styleId != null && styleId != 0) {
			// 系统风格
			AppStyleImgTab img = appService.getAppStyleImgById(styleId, type);
			if (img == null || img.getVarAppStyleImgUrl() == null) {
				return null;
			}
			//解决浏览器缓存图片
			icon.setVarIconUrl(img.getVarAppStyleImgUrl() + "?rand="+Math.random()*100);
		} else {
			return null;
		}
		return icon;
	}
	
	/**
	 * 获得images文件夹下的所有文件名
	 * @return
	 * @author liuhj
	 * 2012-8-8下午06:14:32
	 * @throws IOException 
	 */
	public String listFilesInFolder() throws IOException {
		String path = session.getServletContext().getRealPath("/");
		File folder = new File(path + "produce"+File.separator+"images");
		File file[] = folder.listFiles();
		StringBuffer fileNames = new StringBuffer("[");
		String relativePath = getServerURL().substring(0,
				getServerURL().length() - 1)
				+ request.getContextPath() + "/produce/images/";
		for (int i = 0; i < file.length; i++) {
			fileNames.append("{\"fileName\":\"" + relativePath
					+ file[i].getName() + "\"},");
		}
		jsonOut(fileNames.deleteCharAt(fileNames.lastIndexOf(",")).append("]").toString());
		return null;
	}
	
	/**
	 * 生成二维码
	 * @param content
	 * @param path
	 * @return
	 * @author liuhj
	 * 2012-8-21下午10:35:44
	 * @throws WriterException 
	 * @throws IOException 
	 */
	private void produceQRcode(String content, String path)
			throws WriterException, IOException {
		/*MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
		Map<EncodeHintType, String> arg = new HashMap<EncodeHintType, String>();
		arg.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		BitMatrix bitMatrix = multiFormatWriter.encode(content,
				BarcodeFormat.QR_CODE, 200, 200, arg);
		File file = new File(path);
		MatrixToImageWriter.writeToFile(bitMatrix, "png", file);*/
		
		QRCodeProduceUtil handler = new QRCodeProduceUtil();
		handler.encoderQRCode(content, path, "png");
	}
	
	/**
	 * 查看用户信息
	 * @return
	 * @author liuhj
	 * 2012-8-22上午09:20:18
	 * @throws IOException 
	 */
	public String viewLoginUserInfo() throws IOException {
		JSONObject datas = new JSONObject();
		datas.put("userName", getUserInfo().getVarLoginName());
		jsonOut(datas.toString());
		return null;
	}
	
	/**
	 * 退出登录
	 * @return
	 * @author liuhj
	 * 2012-8-22上午09:22:12
	 */
	public String quitLogin() {
		session.invalidate();
		return SUCCESS;
	}
	
	/**
	 * 查看已生成的应用下载地址及二维码
	 * @return
	 * @author liuhj
	 * 2012-8-22下午06:43:30
	 * @throws IOException 
	 */
	public String viewProducedAppInfo() throws IOException {
		JSONObject dataAndr = new JSONObject();
		//android
		String andrUrl = getUserInfo().getAndroidVersionUpdate().getVarAppDownloadUrl();
		dataAndr.put("type", GenericConstants.OPERATION_SYS_ANDROID);
		dataAndr.put("url", StringUtils.isBlank(andrUrl) ? "-1" : andrUrl);
		String andrQRurl = getServerURL()
				+ getImgBasePath().replaceAll("\\\\", "/")
				+ "/androidQRcode.png";
		dataAndr.put("QRcodeURL", StringUtils.isBlank(andrUrl) ? "-1"
				: andrQRurl);
		// ios
		JSONObject dataIos = new JSONObject();
		String iosDownloadUrl = getUserInfo().getIosVersionUpdate()
				.getVarAppDownloadUrl();
		dataIos.put("type", GenericConstants.OPERATION_SYS_IOS);
		if (StringUtils.isBlank(iosDownloadUrl)) {
			dataIos.put("appStoreUrl", "-1");
			dataIos.put("gotoappUrl", "-1");
		} else {
			if (iosDownloadUrl.contains(",")) {
				String[] urls = StringUtils.split(iosDownloadUrl,",");
				String appStoreUrl = urls[0].contains("_appstore.ipa")?urls[0]:urls[1];
				String gotoappUrl = urls[0].contains("_gotoapp.ipa")?urls[0]:urls[1];
				dataIos.put("appStoreUrl", appStoreUrl);
				dataIos.put("gotoappUrl", gotoappUrl);
			} else {
				dataIos.put("appStoreUrl", "-1");
				dataIos.put("gotoappUrl", iosDownloadUrl);
			}
		}
		String iosQRurl = getServerURL()
				+ getImgBasePath().replaceAll("\\\\", "/") + "/IosQRcode.png";
		dataIos.put("QRcodeURL", StringUtils.isBlank(iosDownloadUrl) ? "-1" : iosQRurl);
		JSONArray ja = new JSONArray();
		ja.add(dataAndr);
		ja.add(dataIos);
		jsonOut(ja.toString());
		return null;
	}
	
	/**
	 * 获取android最新下载地址
	 * @return
	 * @throws IOException
	 */
	public String getLastAndroidDownUrl() throws IOException{
		int appId = Integer.parseInt(request.getParameter("appId"));
		String[] properties = { "varAppDownloadUrl" };
		AppUpdateTab androidAppUpd = appUpdateService.getVersionUpdateInfo(
				appId, properties, GenericConstants.OPERATION_SYS_ANDROID);
		jsonOut(androidAppUpd.getVarAppDownloadUrl()==null?"":androidAppUpd.getVarAppDownloadUrl());
		return null;
	}
	
	/**
	 * 获取IOS最新下载地址
	 * @return
	 * @throws IOException
	 */
	public String getLastIosDownUrl() throws IOException{
		int appId = Integer.parseInt(request.getParameter("appId"));
		String[] properties = { "varAppDownloadUrl" };
		AppUpdateTab iosAppUpd = appUpdateService.getVersionUpdateInfo(
				appId, properties, GenericConstants.OPERATION_SYS_IOS);
		if (!StringUtils.isBlank(iosAppUpd.getVarAppDownloadUrl())) {
			String[] urls = StringUtils.split(iosAppUpd.getVarAppDownloadUrl(),",");
			String gotoappUrl = urls[0].contains("_gotoapp.ipa")?urls[0]:urls[1];
			jsonOut(gotoappUrl);
		} else {
			jsonOut("");
		}
		return null;
	}
	
	/**
	 * 应用版本状态更新[是否需要更新]
	 * @author Taylor
	 * 2012-10-18 下午04:54:03
	 * @return
	 * String
	 * @throws IOException 
	 */
	public String updateVersionState() throws IOException {
		int intState = JSONObject.fromObject(json).getInt("intState");
		int type = JSONObject.fromObject(json).getInt("type");
		if (type == GenericConstants.OPERATION_SYS_ANDROID) {
			appService.updateVersionState(getUserInfo().getAndroidVersionUpdate(), intState);
		} else {
			appService.updateVersionState(getUserInfo().getIosVersionUpdate(), intState);
		}
		jsonOut(GenericConstants.OPERATION_SUCCESS);
		return null;
	}
	
	/**
	 * IOS证书文件上传
	 * @return
	 * @throws IOException
	 * @author liuhj
	 * 2012-7-12下午03:05:17
	 */
	public String iosCerFileUpload() throws IOException {
		String fileName = getIosCerFileName();
		if (fileName == null) {
			jsonOut(GenericConstants.OPERATION_NULL);
			return null;
		}
		String uploadFolder = getWebAppsRealPath() + getImgBasePath() + File.separator + "IOS"+File.separator+"CERTIFICATE";
		File file = new File(uploadFolder);
		if (!file.exists()) {
			file.mkdirs();
		}
		String imgDiskPath = uploadFolder+ File.separator + fileName;
		String imgURLPath = getImgBasePath() + File.separator + "IOS"+File.separator+"CERTIFICATE" + File.separator + fileName;
		FileUploadUtil.fileUpload(imgDiskPath, request,GenericConstants.REQUEST_HEADER_LENGTH);//上传
		jsonOut("{\"url\":\""+(getServerURL()+imgURLPath.replace("\\", "/"))+"\"}");
		return null;
	}
	
	/**
	 * IOS证书文件保存
	 * @author Taylor
	 * 2012-11-27 上午10:19:53
	 * @return
	 * String
	 * @throws IOException 
	 */
	public String updateIosCerFile() throws IOException {
		appService.updateIosCerFile(json, getUserInfo().getAppId());
		jsonOut(GenericConstants.OPERATION_SUCCESS);
		return null;
	}
	
	/**
	 * 根据flag获取IOS证书文件名
	 * @author Taylor
	 * 2012-11-27 上午10:00:56
	 * @return
	 * String
	 */
	private String getIosCerFileName() {
		String requestParams = FileUploadUtil.getParamsFromRequest(request);
		if (!StringUtils.isBlank(requestParams)) {
			String[] params = StringUtils.split(requestParams, ",");
			String flag = params[0].trim();
			if ("appStore_cer".equals(flag)) {
				return "appstore.cer";
			} else if ("appStore_pro".equals(flag)) {
				return "appstore.mobileprovision";
			} else if ("gotoapp_cer".equals(flag)) {
				return "gotoapp.cer";
			} else if ("gotoapp_pro".equals(flag)) {
				return "gotoapp.mobileprovision";
			}
		}
		return null;
	}
	
	/**
	 * 查看IOS证书文件
	 * @author Taylor
	 * 2012-11-26 下午04:48:16
	 * @return
	 * String
	 * @throws IOException 
	 */
	public String viewIosCerFile() throws IOException {
		AppTab app = appService.getAppInfo(getUserInfo().getAppId(), new String[]{"varAppstoreCerUrl","varGotoappCerUrl"});
		String varAppstoreCerUrl = app.getVarAppstoreCerUrl();
		String varGotoappCerUrl = app.getVarGotoappCerUrl();
		JSONArray result = new JSONArray();
		if(!StringUtils.isBlank(varAppstoreCerUrl)){
			String[] urls = StringUtils.split(varAppstoreCerUrl, ";");
			JSONObject jo1 = new JSONObject();
			jo1.put("flag", "appStore_cer");
			jo1.put("url", getServerURL()+ urls[0]);
			JSONObject jo2 = new JSONObject();
			jo2.put("flag", "appStore_pro");
			jo2.put("url", getServerURL()+ urls[1]);
			result.add(jo1);
			result.add(jo2);
		} else {
			JSONObject jo1 = new JSONObject();
			jo1.put("flag", "appStore_cer");
			jo1.put("url", "-1");
			JSONObject jo2 = new JSONObject();
			jo2.put("flag", "appStore_pro");
			jo2.put("url", "-1");
			result.add(jo1);
			result.add(jo2);
		}
		if(!StringUtils.isBlank(varGotoappCerUrl)){
			String[] urls = StringUtils.split(varGotoappCerUrl, ";");
			JSONObject jo3 = new JSONObject();
			jo3.put("flag", "gotoapp_cer");
			jo3.put("url", getServerURL()+ urls[0]);
			JSONObject jo4 = new JSONObject();
			jo4.put("flag", "gotoapp_pro");
			jo4.put("url", getServerURL()+ urls[1]);
			result.add(jo3);
			result.add(jo4);
		} else {
			JSONObject jo3 = new JSONObject();
			jo3.put("flag", "gotoapp_cer");
			jo3.put("url", "-1");
			JSONObject jo4 = new JSONObject();
			jo4.put("flag", "gotoapp_pro");
			jo4.put("url", "-1");
			result.add(jo3);
			result.add(jo4);
		}
		jsonOut("{\"cerFiles\":"+result.toString()+"}");
		return null;
	}

	public List<AppStyleTab> getListAppStyles() {
		return listAppStyles;
	}

	public void setListAppStyles(List<AppStyleTab> listAppStyles) {
		this.listAppStyles = listAppStyles;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getJson() {
		return json;
	}

	public void setJson(String json) {
		this.json = json;
	}

	public String getImgLogoURL() {
		return imgLogoURL;
	}

	public void setImgLogoURL(String imgLogoURL) {
		this.imgLogoURL = imgLogoURL;
	}

	public AppIconTab getAppIconTab() {
		return appIconTab;
	}

	public void setAppIconTab(AppIconTab appIconTab) {
		this.appIconTab = appIconTab;
	}
}
